<?php
namespace Home\Controller;
use Think\Controller;
    define("TOKEN", "07dccb2cfb50dfad0e94d7099c461dc8");
class IndexController extends Controller {
    public function index(){
       $this->responseMsg();
   }
	public function valid(){
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }
    public function responseMsg(){
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

      	//extract post data
		if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
          	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $type = $postObj->MsgType;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[%s]]></MsgType>
				<Content><![CDATA[%s]]></Content>
				<FuncFlag>0</FuncFlag>
				</xml>";
            if ($type=='event'&&$type->Event=="subscribe"){
                $msgType = "text";
                $contentStr = "欢迎您的关注！";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;            
            }                         
			if( $keyword =="你好"){
          		$msgType = "text";
                $contentStr = '<a href="http://www.baidu.com">点我</a>';
            	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            	echo $resultStr;
            }
            $Articles=M('articles')->where(array('keyword'=>$keyword))->select();
            if (!empty($Articles)){
                $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>%s</ArticleCount>
                    <Articles>";
                        foreach ($Articles as $a) {
                        $textTpl.="<item>
                            <Title><![CDATA[".$a['title']."]]></Title> 
                            <Description><![CDATA[".$a['description']."]]></Description>
                            <PicUrl><![CDATA[".$a['picurl']."]]></PicUrl>
                            <Url><![CDATA[".$a['url']."]]></Url>
                        </item>";
                        }
                        $textTpl.="</Articles>
                </xml>"; 
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,count($Articles));
                echo $resultStr;
            }else{
            	$url="http://www.xiaodoubi.com/simsimiapi.php?msg=".$keyword;
				$msgType = "text";
		        $contentStr = http_get($url);
		        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
		        echo $resultStr;
            }
        }else {
        	echo "";
        	exit;
        }
    }
	public function createMenu(){
		$access_token=getAccessToken();
		$url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
		/*$data=' {
			"button":[
			{	
				"type":"click",
				"name":"今日歌曲",
				"key":"V1001_TODAY_MUSIC"
			},
			{
				"name":"菜单",
				"sub_button":[{	
					"type":"view",
					"name":"搜索",
					"url":"http://www.soso.com/"
					},
				{	
					"type":"view",
					"name":"视频",
					"url":"http://v.qq.com/"
					},
				{
					"type":"click",
					"name":"赞一下我们",
					"key":"V1001_GOOD"
				}]
			}]
		}';*/
		$data=array(
			'button'=>array(
				array(
					'name'=>"扫码",
					'sub_button'=>array(
						array(
							'type'=>"scancode_waitmsg",
							'name'=>"扫码带提示",
							'key'=>"rselfmenu_0_0",
						),
						array(
							'type'=>"scancode_push",
							'name'=>"扫码推事件",
							'key'=>"rselfmenu_0_1",
						),
					),
				),
				array(
					'name'=>"发图",
					'sub_button'=>array(
						array(
							'type'=>"pic_sysphoto",
							'name'=>"系统拍照发图",
							'key'=>"rselfmenu_1_0",
						),
						array(
							'type'=>"pic_photo_or_album",
							'name'=>"拍照或者相册发图",
							'key'=>"rselfmenu_1_1",
						),
						array(
							'type'=>"pic_weixin",
							'name'=>"微信相册发图",
							'key'=>"rselfmenu_1_2",
						),
					),
				),
				array(
					'name'=>"位置信息",
					'sub_button'=>array(
						array(
							'type'=>"location_select",
							'name'=>"发送位置",
							'key'=>"rselfmenu_2_0",
						),	
					),
				),
			),
		);
		$data=json_encode($data,JSON_UNESCAPED_UNICODE);
		$a=http_post($url,$data);
		var_dump($a);
	}	
	private function checkSignature(){
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}